package com.gzhryc.common;

import java.awt.*;
import java.awt.image.BufferedImage;

public class ImageTools {

    public static boolean needThumbnail(BufferedImage originalImage, Integer thumbWidth, Integer thumbHeight){
        double scale = Math.max((double) thumbWidth / originalImage.getWidth(), (double) thumbHeight / originalImage.getHeight());
        if(scale > 1) {
            return false;
        }
        return true;
    }

    public static BufferedImage thumbnail(BufferedImage originalImage, Integer thumbWidth, Integer thumbHeight){
        // 计算缩放比例
        double scale = Math.min((double) thumbWidth / originalImage.getWidth(), (double) thumbHeight / originalImage.getHeight());
        if(scale != 0) {
            // 新建缩略图大小
            int newWidth = (int) (originalImage.getWidth() * scale);
            int newHeight = (int) (originalImage.getHeight() * scale);

            Image thumbnail = originalImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);

            BufferedImage newImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = newImage.createGraphics();
            graphics2D.drawImage(thumbnail, 0, 0, null);
            graphics2D.dispose();
            return newImage;
        }else{
            return originalImage;
        }
    }


    public static BufferedImage thumbnailAndCropping(BufferedImage originalImage, Integer thumbWidth, Integer thumbHeight){
        double scale = Math.max((double) thumbWidth / originalImage.getWidth(), (double) thumbHeight / originalImage.getHeight());
        if(scale != 0) {
            // 新建缩略图大小
            int newWidth = (int) (originalImage.getWidth() * scale);
            int newHeight = (int) (originalImage.getHeight() * scale);

            Image thumbnail = originalImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);

            BufferedImage newImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = newImage.createGraphics();
            graphics2D.drawImage(thumbnail, 0, 0, null);
            graphics2D.dispose();

            //裁剪
            // 计算开始裁剪的位置
            int startX = (newImage.getWidth() - thumbWidth) / 2;
            int startY = (newImage.getHeight() - thumbHeight) / 2;
            BufferedImage croppedImage = newImage.getSubimage(startX, startY, thumbWidth, thumbHeight);

            return croppedImage;
        }else{
            return originalImage;
        }
    }
}
